// manager/pages/editposter/index.js
import config from '../../../utils/config';
import { request, uploadFile } from '../../../utils/request';
import Wxml2Canvas from '../../wxml2canvas/index';
import Util from '../../wxml2canvas/util';
Page({
    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: config.baseUrl,
		posterType: "",
		posterId: "",
		posterTitle: "",
		posterDetails: "",
		posterEditSts: "",
		showCanvas: false,
		current: 0,
		currentPoster: {},
		posterList: [],
		userInfo: {},
        showSetup: false,
        qrCodeType: "",
		qrCodeList: [
            // type >>> 1 个人名片   2 自定义二维码
            {id: 1, type: 1, text: "个人名片"},
            {id: 2, type: 2, text: "自定义二维码"},
        ],
        // 个人名片二维码
        weChatQrCode: "",
        // 自定义二维码
        customQrCode: "",
        showCropper: false,
        // 个人信息列表
		userEditList: [
			// {id: 1, type: "headUrl", text: "头像"},
			// {id: 2, type: "userName", text: "姓名"},
			// {id: 3, type: "deptName", text: "公司"},
			// {id: 4, type: "postName", text: "职位"},
			// {id: 5, type: "phoneno", text: "电话"},
        ],
        // 选中的个人信息
        userCheckedList: [],
        // 保存分享设置的数据
		setupData: {
            qrCodeUrl: "",
			qrCodeSwitch: true,
			qrCodeClew: "",
			userInfoSwitch: true,
			headUrl: "",
			userName: "",
			deptName: "",
			postName: "",
			phoneno: "",
        },
        // 编辑分享设置的数据
		editSetupData: {
            qrCodeUrl: "",
			qrCodeSwitch: true,
			qrCodeClew: "",
			userInfoSwitch: true,
			headUrl: "",
			userName: "",
			deptName: "",
			postName: "",
			phoneno: "",
        },
        
		generatePoster: "",
		showPosterPopup: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
		this.setData({
            posterId: options.posterId,
            posterType: options.posterType
		})
		this.getPosterList();
	},
	

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        // this.drawImage();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

	},

	// 获取用户登录信息
    getUserInfo() {
        request({
            url: "/user/getUserInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {}
        }).then(res => {
            if(res.code == 0){
                let userInfo = res.data.userInfo;
                this.setData({
                    userInfo
                })
                this.getUserEditList();
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    // 获取分享设置个人信息字典
    getUserEditList() {
        request({
            url: "/commonApi/getDictionaryInfo",
            method: "GET",
            data: {
				dictType: "ecard_poster_share_ att"
			}
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    userEditList: res.data
                })
                this.getWeChatQrCode();
                this.getMyPrdDefinedSkip();
            }
        }).catch(error => {
            // console.log(error)
        })
    },
	// 获取分享设置保存配置
	getMyPrdDefinedSkip(callback) {
        request({
            url: "/poster/getMyPrdDefinedSkip",
            method: "GET"
        }).then(res => {
            if(res.code == 0){
                if(res.data){
                    console.log("我有配置了")
                    let { editSetupData, userInfo } = this.data;
                    let data = res.data;
                    for(let key in editSetupData){
                        if(key == "qrCodeSwitch" || key == "userInfoSwitch"){
                            editSetupData[key] = data[key] == 1 ? true : false;
                        }else if(key == "qrCodeUrl") {
                            if(data[key]){
                                editSetupData[key] = this.data.baseUrl + data[key];
                            }else{
                                editSetupData[key] = "";
                            }
                        }else{
                            editSetupData[key] = data[key] ? data[key] : "";
                        }
                    }
                    let userCheckedList = data.userInfo.split(",");
                    userCheckedList.forEach(item => {
                        editSetupData[item] = userInfo[item];
                    })
                    let setupData = JSON.parse(JSON.stringify(editSetupData));
                    let that = this;
                    this.setData({
                        qrCodeType: data.qrCodeType,
                        
                        setupData,
                        userCheckedList
                    })
                    wx.getImageInfo({
                        src: editSetupData.qrCodeUrl,
                        success (res) {
                            editSetupData.qrCodeUrl = res.path;
                            that.setData({
                                editSetupData,
                                customQrCode: data.qrCodeType == 2 ? res.path : "",
                            })
                        }
                    })
                }
                callback&&callback()
            }
        }).catch(error => {
            // console.log(error)
        })
		
    },
    // 获取小程序二维码
    getWeChatQrCode() {
        request({
            url: "/poster/getWeChatQrCode",
            method: "GET"
        }).then(res => {
            if(res.code == 0){
                // 将base64转本地路径
                let uid = Util.getUid();
                let filename = `${wx.env.USER_DATA_PATH}/${uid}.png`;
                let fileManager = wx.getFileSystemManager();
                let that = this;
                fileManager.writeFile({
                    filePath: filename,
                    data: res.data.replace(/data:image\/(.*);base64,/, ''),
                    encoding: 'base64',
                    success (res) {
                        that.setData({
                            weChatQrCode: filename
                        })
                    },
                    fail (res) {
                        reject(res);
                    },
                })
                
            }
        }).catch(error => {
            // console.log(error)
        })
	},
	/** 获取全部海报列表 */
    getPosterList(e) {
        if(this.data.posterType == "zizhi"){
            // 自制模板海报
            request({
                url: "/poster/getMyMakePosterList",
                method: "GET",
            }).then(res => {
                if(res.code == 0){
					let current = res.data.findIndex(item => item.id == this.data.posterId);
					let item = res.data[current];
                    this.setData({
						current,
						posterTitle: item.title || "自制模板",
						posterDetails: item.details || "",
						posterEditSts: item.editSts || 1,
                        posterList: res.data
					})
					wx.setNavigationBarTitle({
						title: `${item.title || '自制模板'}`
                    })
                    this.getUserInfo();
                }
            })
        }else{
            // 海报列表
            request({
                url: "/poster/getOrganPosterList",
                method: "GET",
                data: this.data.posterType ? { posterType: this.data.posterType } : {}
            }).then(res => {
                if(res.code == 0){
                    let current = res.data.findIndex(item => item.id == this.data.posterId);
                    let item = res.data[current];
                    this.setData({
						current,
						posterTitle: item.title,
						posterDetails: item.details,
						posterEditSts: item.editSts,
                        posterList: res.data
					})
					wx.setNavigationBarTitle({
						title: `${item.title || ''}`
                    })
                    this.getUserInfo();
                }
            })
        }
	},

    // 切换
    swiperChange(e){
		let { current } = e.detail;
		let item = this.data.posterList[current];
		wx.setNavigationBarTitle({
			title: `${item.title || '自制模板'}`
        })
		if(this.data.posterType == "zizhi"){
			this.setData({
				posterId: item.id,
				posterTitle: item.title || "自制模板",
				posterDetails: item.details || "",
				posterEditSts: item.editSts || 1,
				current
			})
			return
		}
        this.setData({
			posterId: item.id,
			posterTitle: item.title,
			posterDetails: item.details,
			posterEditSts: item.editSts,
            current
		})
    },

	// 生成海报
    drawImage () {
		let self = this;
		wx.showLoading({
            title:"海报生成中",
            mask: true 
        })
		const query = wx.createSelectorQuery()
		query.select('.swiper-active').boundingClientRect()
		query.selectViewport().scrollOffset()
		query.exec((res) => {
			console.log(res)
			this.setData({
                showCanvas: true,
				canvasHeight: res[0].height
			})
			let drawImage = new Wxml2Canvas({
				width: res[0].width,
				height: res[0].height,
				element: 'canvas1',
				background: '#fff',
				zoom: 1,
				progress (percent) {
				},
				finish(url) {
					wx.hideLoading()
					// 生成海报图片地址
					self.setData({
						showCanvas: false,
						generatePoster: url,
						showPosterPopup: true
					})
					uploadFile({
						url: "/poster/addPosterShare",
                        filePath: url,
                        beforeTitle: "海报保存中",
                        afterTitle: "海报保存成功！",
						name: "imageFile",
						formData: {
							posterId: self.data.posterId,
							// 是否自制(1,是，2否)
							isMake: self.data.posterType == "zizhi" ? 1 : 2
						}
					}).then(res => {
						if(res.code == 0){
							
						}
					}).catch(error => {
						// console.log(error)
					})
				},
				error (res) {
				}
			});
			let data = {
				list: [{
					type: 'wxml',
					class: '.swiper-active .draw_canvas',
					limit: '.swiper-active',
					x: 0,
					y: 0
				}]
			}
			drawImage.draw(data);
		})
        
    },
    /** 输入框输入时 */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['editSetupData.'+key]: e.detail.value
        })
    },
	/** 分享设置 */
	setup(e){
		// editSts  1 可编辑  2 不可编辑
		if(this.data.posterEditSts == 2){
			wx.showToast({
				title: "当前海报不可自定义编辑！",
				icon: 'none',
				duration: 2000
			});
			return
		}
		this.setData({
			showSetup: true
		})
	},
    /** 分享设置二维码开关 */
    qrCodeSwitchChange(e){
        this.setData({
            "editSetupData.qrCodeSwitch": e.detail
        });
	},
    /** 分享设置选择二维码 */
    qrCodeSingleChoice(e){
        let { type } = e.currentTarget.dataset;
        if(!this.data.editSetupData.qrCodeSwitch){
            return
        }
        this.setData({
            // qrCodeType: this.data.qrCodeType == type ? "" : type,
            qrCodeType: type,
            "editSetupData.qrCodeUrl": type == 2 ? this.data.customQrCode : this.data.weChatQrCode
        });
    },
    /** 分享设置显示上传自定义二维码弹窗 */
    showCustomQR(){
        this.setData({
            showCropper: true
        })
    },
    /** 分享设置关闭自定义二维码弹窗 */
    cropperClose(e){
        this.setData({
            showCropper: false
        })
    },
    /** 分享设置上传自定义二维码 */
    cropperUpload(e){
        this.setData({
            "editSetupData.qrCodeUrl": e.detail.url,
            customQrCode: e.detail.url,
            showCropper: false
        })
		// wx.getFileSystemManager().readFile({
		// 	filePath: e.detail.url, //选择图片返回的相对路径
		// 	encoding: 'base64', //编码格式
		// 	success: res => { //成功的回调
		// 		console.log('data:image/png;base64,' + res.data)
		// 		this.setData({
		// 			"setupData.qrCodeUrl": 'data:image/png;base64,' + res.data,
		// 			showCropper: false
		// 		})
		// 	}
		// })
    },
    /** 分享设置个人信息开关 */
    userInfoSwitchChange(e){
        this.setData({
            "editSetupData.userInfoSwitch": e.detail
        });
	},
	/** 分享设置选择个人信息 */
	userMultChoice(e){
        let { type } = e.currentTarget.dataset;
        let { userInfo, userCheckedList, editSetupData } = this.data;
        if(!this.data.editSetupData.userInfoSwitch){
            return
        }
        let index = userCheckedList.indexOf(type);
        if(index != -1){
            editSetupData[type] = "";
            userCheckedList.splice(index,1);
        }else{
            editSetupData[type] = userInfo[type];
            userCheckedList.push(type);
        }
        this.setData({
            userCheckedList,
            editSetupData
        });
    },

	/** 分享设置取消 */
	closeSetup(e){
		this.setData({
			showSetup: false
		})
	},
	/** 分享设置确认 */
	confirmSetup(e){
		let { setupData, editSetupData, userCheckedList } = this.data;
		let data = {
			qrCodeSwitch: "",
			// qrCodeUrl: "",
			qrCodeClew: "",
			userInfoSwitch: "",
            userInfo: "",
            oldQrCodeUrl: "",
            qrCodeType: ""
        };
        if(this.data.qrCodeType == 2&&!editSetupData.qrCodeUrl){
            wx.showToast({
				title: "请上传自定义二维码！",
				icon: 'none',
				duration: 2000
			});
            return
        }
        if(editSetupData.qrCodeClew&&!/^[\u4e00-\u9fa5]{1,8}$/.test(editSetupData.qrCodeClew)){
            wx.showToast({
				title: "二维码提示语为中文",
				icon: 'none',
				duration: 2000
			});
            return
        }
        for(let key in data){
			if(key == "qrCodeSwitch" || key == "userInfoSwitch"){
				data[key] = editSetupData[key] ? 1 : 2;
			}else{
				data[key] = editSetupData[key] ? editSetupData[key] : "";
			}
        }
        data.oldQrCodeUrl = this.data.setupData.qrCodeUrl;
        data.qrCodeType = this.data.qrCodeType;
        data.userInfo = userCheckedList.join(',');
		// 保存分享配置
		uploadFile({
			url: "/poster/addPosterShareConf",
            filePath: editSetupData.qrCodeUrl,
            beforeTitle: "加载中...",
            afterTitle: "保存成功",
			name: "imageFile",
			formData: data
		}).then(res => {
			if(res.code == 0){
				this.setData({
					showSetup: false
                })
                this.getMyPrdDefinedSkip(() => {
                    wx.showToast({
                        title: "保存成功!",
                        icon: 'none',
                        duration: 2000
                    });
                });
			}
		}).catch(error => {
			// console.log(error)
		})
	},
    /** 生成海报 */
    generatePoster(e){
        this.drawImage();
	},
	/** 关闭海报弹窗 */
	posterClose(e){
        this.setData({
            showPosterPopup: false
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },
})